#include "config.h" //通用配置头文件
#include "isr.h"
#define __SYSTICK
// #define EXTI
#define __TIMER
// #define __UART
#define __PWM
#define __ADC
#ifdef __SYSTICK

// uint16_t debug[16];
// SysTick interrupt handler - called every 1 ms (configured by SysConfig)
void SysTick_Handler(void)
{
	msTicks++;
}
#endif

#ifdef __EXTI
/*
 * Group1 IRQ handler handles GPIOA interrupts among others.
 * SysConfig enabled PA7 (GPIOA pin 7) as falling edge interrupt.
 */
void GROUP1_IRQHandler(void)
{
	/* Check if GPIOA PA7 triggered (enabled interrupt status) */
	if (DL_GPIO_getEnabledInterruptStatus(ENCODER_PORT, ENCODER_EC11_KEY_PIN) & ENCODER_EC11_KEY_PIN)
	{
		/* Clear the interrupt flag for PA7 */
		DL_GPIO_clearInterruptStatus(ENCODER_PORT, ENCODER_EC11_KEY_PIN);
		/* Set a flag for the main loop or other tasks to process */
		encoderEvent = 1;
	}

	/* If other Group1 sources exist, optionally check/clear them here.
	 * DL_Interrupt_getStatusGroup and DL_Interrupt_clearGroup can be used
	 * for group-level handling if needed.
	 */
}

#endif
#ifdef __PWM

void PWM_0_INST_IRQHandler(void)
{
	switch (DL_TimerG_getPendingInterrupt(PWM_0_INST))
	{
	case DL_TIMERG_IIDX_LOAD:
		PWMB_isr(); // 调用PWM中断服务程序
		break;
	default:
		break;
	}
}

#endif

#ifdef __TIMER

void TIMER_0_INST_IRQHandler(void)
{
	switch (DL_TimerG_getPendingInterrupt(TIMER_0_INST))
	{
	case DL_TIMERG_IIDX_ZERO:
		TM0_isr(); // 调用定时器中断服务程序
		break;

	default:
		break;
	}
}

#endif

#ifdef __UART
volatile bool gUartDMARXdone = false; // DMA接收完成标志
volatile bool gUartDMATXdone = true;  // DMA发送完成标志
void UART_0_INST_IRQHandler(void)
{
	// Check if RX interrupt is pending
	switch (DL_UART_getPendingInterrupt(UART_0_INST))
	{
	case DL_UART_IIDX_DMA_DONE_RX:
		// DMA接收完成，处理接收到的数据
		break;
	case DL_UART_IIDX_DMA_DONE_TX:
		// DMA发送完成，构造新帧准备下次传输
		break;
	case DL_UART_IIDX_RX_TIMEOUT_ERROR:
		// 接收超时，清空FIFO并重新对齐DMA
		DL_DMA_disableChannel(DMA, DMA_CH0_CHAN_ID);

		// 清空UART RX FIFO（读取所有残留数据直到FIFO为空）
		while (DL_UART_isRXFIFOEmpty(UART_0_INST) == false)
		{
			DL_UART_receiveData(UART_0_INST); // 丢弃数据
		}

		// 重新设置DMA接收通道（从缓冲区起始位置重新对齐）
		DL_DMA_setSrcAddr(DMA, DMA_CH0_CHAN_ID, (uint32_t)(&UART_0_INST->RXDATA));
		DL_DMA_setDestAddr(DMA, DMA_CH0_CHAN_ID, (uint32_t)&gReceiveBuffer);
		DL_DMA_setTransferSize(DMA, DMA_CH0_CHAN_ID, sizeof(gReceiveBuffer));

		// 重新启用DMA接收通道
		DL_DMA_enableChannel(DMA, DMA_CH0_CHAN_ID);
		break;
	default:
		break;
	}
}
#endif

#ifdef __ADC
void ADC12_0_INST_IRQHandler(void)
{
	switch (DL_ADC12_getPendingInterrupt(ADC12_0_INST))
	{
	case DL_ADC12_IIDX_MEM7_RESULT_LOADED:
		// 读取ADC结果
		// 设置数据准备就绪标志
		break;

	default:
		break;
	}
}

#endif